package com.ladlee.parking.controller;

import com.ladlee.parking.entity.SecurityUser;
import com.ladlee.parking.entity.vo.MenuVO;
import com.ladlee.parking.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collections;
import java.util.List;

@RestController
public class LoginController {

    @Autowired
    PersistentTokenRepository tokenRepository;
    @Autowired
    SysMenuService sysMenuService;

    @GetMapping(value = "/")
    public ModelAndView index(Authentication authentication) {
        ModelAndView view = new ModelAndView();
        if (authentication != null) {
            view.setViewName("redirect:/token/index");
        } else {
            view.addObject("name", "");
            view.addObject("password", "");
            view.addObject("msg", "");
            view.setViewName("ftl/login");
        }
        return view;
    }

    @GetMapping("/token/login")
    public ModelAndView require(ModelAndView modelAndView, @RequestParam(required = false) String error) {
        modelAndView.setViewName("ftl/login");
        modelAndView.addObject("error", error);
        return modelAndView;
    }

    @GetMapping(value = "/token/index")
    public ModelAndView index(ModelAndView view, Authentication authentication) {
        if (authentication == null) {
            view.addObject("error", "登录超时！");
            view.setViewName("ftl/login");
            return view;
        }
        //根据用户角色获取相应菜单
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUser) {
            SecurityUser securityUser = (SecurityUser) principal;
            List<MenuVO> menuTree = securityUser.getMenuTree();
            view.addObject("menuTree", menuTree);
        }
        view.setViewName("ftl/index");
        return view;
    }

    @GetMapping(value = "/token/logout")
    public ModelAndView logout(ModelAndView modelAndView) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
            tokenRepository.removeUserTokens(securityUser.getUsername());
            SecurityContextHolder.clearContext();
        }
        modelAndView.setViewName("ftl/login");
        return modelAndView;
    }
}
